<template>
  <!-- 打卡日历页面 -->
  <view class="all">
    <view class="bar">
      <!-- 上一个月 -->
      <view class="previous" @click="handleCalendarPrev" style="transform: scaleX(-1)">
        <image src="../../static/icon/right.png"></image>
      </view>
      <!-- 显示年月 -->
      <view class="date">{{ cur_year }} 年 {{ cur_month }} 月</view>
      <!-- 下一个月 -->
      <view class="next" @click="handleCalendarNext">
        <image src="../../static/icon/right.png"></image>
      </view>
    </view>
    <view class="days">
      <!-- 显示星期 -->
      <view class="week">
        <view v-for="(item, index) in weeks_ch" :key="index">{{ item }}</view>
      </view>
      <!-- 列 -->
      <view class="columns" v-for="(item, i) in 7" :key="i">
        <view v-for="(items, j) in days" :key="j">
          <!-- 行 -->
          <view class="rows" v-if="j / 7 == i">
            <view class="rows" v-for="(item, k) in 7" :key="k">
              <!-- 每个月份的空的单元格 -->
              <view class="cell" v-if="days[j + k] == 0">
                <text decode="true">&nbsp;&nbsp;</text>
              </view>
              <!-- 每个月份的有数字的单元格 -->
              <view class="cell" v-else>
                <!-- 当前日期已签到  且正常出勤-->
                <!-- :class=" days[j + k] === activeItemIndex ? 'active' : 'active2'" -->
                <view v-if="days_sign_up[j + k] == 1" @click="handleTest(days[j + k], $event)" :data-index="days[j + k]"
                  :class="
                    days[j + k] === activeItemIndex ? 'select' : 'noSelect'
                  " style="background-color: #83c75d" class="cell">
                  <!-- style="background-color: #83c75d; color: #fff" -->
                  <view>
                    <text>{{ days[j + k] }}</text>
                  </view>
                  <!-- <view class="test" style="background: #83c75d"></view> -->
                </view>
                <!-- 当前日期也签单 但迟到 -->
                <!-- :class=" days[j + k] === activeItemIndex ? 'active' : 'active2'" -->
                <view v-else-if="days_sign_up[j + k] == 0" @click="handleTest(days[j + k], $event)"
                  :data-index="days[j + k]" :class="
                    days[j + k] === activeItemIndex ? 'select' : 'noSelect'
                  " style="background-color: #fabc05" class="cell">
                  <!-- style="background-color: #fabc05; color: #fff" -->
                  <view>
                    <text>{{ days[j + k] }}</text>
                  </view>
                  <!-- <view class="test" style="background: #fabc05"></view> -->
                </view>
                <!-- 当前日期未签到 -->
                <view v-else @click="handleTest(days[j + k], $event)" :class="
                    days[j + k] === activeItemIndex ? 'active' : 'active2'
                  " :data-index="days[j + k]">
                  <view>
                    <text>{{ days[j + k] }}</text>
                  </view>
                  <view class="test"></view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="explain">
        <view>
          <view class="normal"></view>
          <view class="info">全天考勤正常</view>
        </view>
        <view>
          <span class="abnormal"></span>
          <span class="info">当天存在异常：迟到、早退、缺卡、外勤</span>
        </view>
      </view>
      <view class="steps">
        <van-steps class="stepsStyle" direction="vertical" active-color="#38f" :steps="steps">
        </van-steps>
      </view>
    </view>
    <!-- 坚持打卡天数 -->
    <view class="count">
      <text>{{ cur_year + "-" + cur_month }}，你已坚持打卡</text>
      <view class="daynumber">
        <text class="number">{{ count }}</text>
        <text class="day">天</text>
      </view>
      <text>请再接再厉，继续努力</text>
    </view>
  </view>
</template>

<script>
  import { getCheckStatus } from "@/utils/api/kaoqin.js";
  import { checkPosition, queryDay } from "@/utils/api/check.js";
  import QQMapWX from "../../../static/qqmap/qqmap-wx-jssdk.min";
  export default {
    data() {
      return {
        // objectId: '',
        days: [], // days他这里表示日期，属性 isSign==true 的就是已签到的，那我就把days放1-31（含空白格子 +  当前月份 日子数），days_sign_up放对应个数的-1，如果有日期签到，就把对应的days_sign_up置0 or 1，根据数据库中我存储的 state而修改
        days_sign_up: [],
        signUp: [],
        cur_year: 0,
        cur_month: 0,
        count: 0,
        weeks_ch: [],
        userCode: "",
        steps: [],
        activeItemIndex: 0,
        isClasses: "",
        dkBanci: "",
        dkLunGang: "",
        dkDeploy: "",
        dkDeployList: [],
        monthList: [],
      };
    },
    onLoad: function (options) {
      this.userCode = wx.getStorageSync("usercode"); // 获取
      this.getLocation();
      //获取当前年月
      const date = new Date();
      const cur_year = date.getFullYear();
      const cur_month = date.getMonth() + 1;
      const cur_day = date.getDate();
      this.activeItemIndex = cur_day;
      const weeks_ch = ["日", "一", "二", "三", "四", "五", "六"];
      this.cur_year = cur_year;
      this.cur_month = cur_month;
      this.weeks_ch = weeks_ch;
      // this.queryDay(cur_year, cur_month, cur_day);
      // 计算当月1号前面应该空的格子数
      this.calculateEmptyGrids(cur_year, cur_month);
      // 计算天数
      this.calculateDays(cur_year, cur_month);
    },
    methods: {
      handleTest(day, e) {
        this.activeItemIndex = e.currentTarget.dataset.index;
        this.queryDay(this.cur_year, this.cur_month, day);
      },
      // 获取当月共多少天
      getThisMonthDays: function (year, month) {
        return new Date(year, month, 0).getDate();
      },
      // 获取当月第一天星期几
      getFirstDayOfWeek: function (year, month) {
        return new Date(Date.UTC(year, month - 1, 1)).getDay();
      },
      // 计算当月1号前空了几个格子，把它填充在days数组的前面
      calculateEmptyGrids: function (year, month) {
        var that = this;
        //计算每个月时要清零
        that.days = [];
        that.days_sign_up = [];
        const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
        let days = that.days;
        let days_sign_up = that.days_sign_up;
        if (firstDayOfWeek > 0) {
          for (let i = 0; i < firstDayOfWeek; i++) {
            days.push(0);
            days_sign_up.push(-1);
          }
          that.days = days;
          that.days_sign_up = days_sign_up;
          //清空
        } else {
          that.days = [];
          that.days_sign_up = [];
        }
        // console.log(this.days.length);
        // console.log(this.days_sign_up.length);
      },
      // 绘制当月天数占的格子，并把它放到days数组中
      calculateDays: function (year, month) {
        var that = this;
        const thisMonthDays = this.getThisMonthDays(year, month);
        let days = that.days;
        let days_sign_up = that.days_sign_up;
        for (let i = 1; i <= thisMonthDays; i++) {
          days.push(i);
          days_sign_up.push(-1);
        }
        that.days = days;
        that.days_sign_up = days_sign_up;
      },
      handleCalendarPrev() {
        this.activeItemIndex = 1;
        const cur_year = this.cur_year;
        const cur_month = this.cur_month;
        let newMonth = cur_month - 1;
        let newYear = cur_year;
        if (newMonth < 1) {
          newYear = cur_year - 1;
          newMonth = 12;
        }
        // 切换年月后 一定要先设置this的数据 再运行别的函数 否则会有冲突
        this.cur_year = newYear;
        this.cur_month = newMonth;
        this.calculateEmptyGrids(newYear, newMonth);
        this.calculateDays(newYear, newMonth);
        this.handleGetStatus(newYear, newMonth);
        this.queryDay(newYear, newMonth, 1);
      },
      handleCalendarNext() {
        this.activeItemIndex = 1;
        const cur_year = this.cur_year;
        const cur_month = this.cur_month;
        let newMonth = cur_month + 1;
        let newYear = cur_year;
        if (newMonth > 12) {
          newYear = cur_year + 1;
          newMonth = 1;
        }
        this.cur_year = newYear;
        this.cur_month = newMonth;
        this.calculateEmptyGrids(newYear, newMonth);
        this.calculateDays(newYear, newMonth);
        this.handleGetStatus(newYear, newMonth);
        this.queryDay(newYear, newMonth, 1);
      },
      onGetSignUp(a, b) {
        this.count = 0;
        var days = this.days;
        var days_sign_up = this.days_sign_up;
        var cur_year = this.cur_year;
        var cur_month = this.cur_month;
        var count = 0;
        let t_date = a;
        let t_state = b;
        // 对于已经签到的每一个日期
        for (let i = 0; i < t_date.length; i++) {
          // 如果是当前年份当前月份，就置days_sign_up为true  //2017-04-03
          let year = parseInt(t_date[i].substring(0, 4));
          let month = parseInt(t_date[i].substring(5, 7));
          let day = parseInt(t_date[i].substring(8, 10));
          for (let j = 0; j < days.length; j++) {
            if (year == cur_year && month == cur_month && day == days[j]) {
              days_sign_up[j] = t_state[i];
              count = count + 1;
            }
          }
          this.days = days;
          this.days_sign_up = days_sign_up;
          this.count = count;
        }
      },
      handleGetStatus(cur_year, cur_month) {
        if (cur_month < 10) {
          let month = "0" + cur_month;
          if (this.isClasses === "0" || this.isClasses === "1") {
            this.getCheckStatus({
              userCode: this.userCode,
              dkTime: cur_year + "-" + month,
              dkBanci: this.dkBanci,
              isClasses: this.isClasses,
              dkLunGang: "6",
            });
          } else {
            this.getCheckStatus({
              userCode: this.userCode,
              dkTime: cur_year + "-" + month,
              dkBanci: this.dkBanci,
              isClasses: this.isClasses,
              dkLunGang: this.dkLunGang,
            });
          }
        } else {
          let month = cur_month + ''
          if (this.isClasses === "0" || this.isClasses === "1") {
            this.getCheckStatus({
              userCode: this.userCode,
              dkTime: cur_year + "-" + month,
              dkBanci: this.dkBanci,
              isClasses: this.isClasses,
              dkLunGang: "6",
            });
          } else {
            this.getCheckStatus({
              userCode: this.userCode,
              dkTime: cur_year + "-" + month,
              dkBanci: this.dkBanci,
              isClasses: this.isClasses,
              dkLunGang: this.dkLunGang,
            });
          }
        }
      },
      getLocation() {
        wx.getLocation({
          type: "gcj02",
          isHighAccuracy: true,
          success: (res) => {
            let qqmapsdk = new QQMapWX({
              // key: "GZ5BZ-OAXED-DNM4H-HMVLD-5BIXO-XFBMX",
              key: "PVDBZ-WSNKI-JFIGK-UBGZT-XRLK5-UCBZC",
            });
            this.longitude = res.longitude;
            this.latitude = res.latitude;
            let data = {
              latitude: this.latitude,
              longitude: this.longitude,
            };
            this.checkPosition(data);
          },
        });
      },
      //获取当前用户的考勤数组并匹配那些日子打卡
      async getCheckStatus(data) {
        try {
          let res = await getCheckStatus(data);
          if (res.code == 200) {
            this.monthList = res.data.monthList;
            this.dkDeployList = res.data.dkDeployList;
            let arr = [];
            res.data.typeList.forEach((item) => {
              arr.push(Number(item));
            });
            this.onGetSignUp(res.data.monthList, arr);
            const date = new Date();
            const cur_year = date.getFullYear();
            const cur_month = date.getMonth() + 1;
            const cur_day = date.getDate();
            this.queryDay(cur_year, cur_month, cur_day);
          }
        } catch (error) {
          console.log(error);
        }
      },
      async queryDay(year, month, day) {
        this.steps = [];
        let arr1 = [];
        if (month < 10) {
          month = "0" + month;
        }
        if (day < 10) {
          day = "0" + day;
        }
        let yearMonthDay = year + "-" + month + "-" + day;
        let exists = this.monthList.includes(yearMonthDay);
        if (exists) {
          var index = this.monthList.indexOf(yearMonthDay);
        }
        try {
          let res = await queryDay({
            dkTimeDay: year + "-" + month + "-" + day,
            isClasses: this.isClasses,
            dkLunGang: this.dkLunGang,
            dkDeploy: this.dkDeployList[index],
          });
          if (res.code == 200) {
            res.data.forEach((item, index) => {
              if (item.up) {
                if (item.up.dkType === '1') {
                  arr1.push({ dkTime: item.up.dkTime.slice(11, 16), drType: '(地址：正常', dkType: '类型：' + item.up.isycName + ')' });
                } else if (item.up.dkType === '2') {
                  arr1.push({ dkTime: item.up.dkTime.slice(11, 16), drType: '(地址：外勤', dkType: '类型：' + item.up.isycName + ')' });
                }
              }
              if (item.down) {
                if (item.down.dkType === '1') {
                  arr1.push({ dkTime: item.down.dkTime.slice(11, 16), drType: '(地址：正常', dkType: '类型：' + item.down.isycName + ')' });
                } else if (item.down.dkType === '2') {
                  arr1.push({ dkTime: item.down.dkTime.slice(11, 16), drType: '(地址：外勤', dkType: '类型：' + item.down.isycName + ')' });
                }
              }
            });
            arr1.forEach((item, index) => {
              if (index % 2 === 0) {
                this.steps.unshift({
                  text: "上班打卡：" + item.dkTime + '-' + item.drType + '，' + item.dkType,
                });
              } else if (index % 2 === 1) {
                this.steps.unshift({
                  text: "下班打卡：" + item.dkTime + '-' + item.drType + '，' + item.dkType,
                });
              }
            });
            // if (res.data.down) {
            //   this.steps.push({
            //     text: "下班打卡：" + res.data.down.dkTime.slice(-9),
            //   });
            // }
            // if (res.data.up) {
            //   this.steps.push({
            //     text: "上班打卡：" + res.data.up.dkTime.slice(-9),
            //   });
            // }
          }
        } catch (error) {
          console.log(error);
        }
      },
      // 不自动-判断当前位置审核状态
      async checkPosition(data) {
        try {
          let res = await checkPosition(data);
          if (res.code == 200) {
            this.isClasses = res.data.configBase.isClasses;
            this.dkBanci = res.data.configBase.dkBanci;
            this.dkLunGang = res.data.configBase.dkLungang;
            this.dkDeploy = res.data.dkDeploy;
            //获取当前用户当前任务的签到状态
            this.handleGetStatus(this.cur_year, this.cur_month);
          } else if (res.code == 401) {
            Dialog.confirm({
              title: "重新登录",
              message: "当前身份信息已过期，请重新登录",
            })
              .then(() => {
                wx.clearStorage({
                  success: function (res) {
                    wx.navigateTo({
                      url: "/pages/login/main",
                    });
                  },
                });
              })
              .catch(() => {
                wx.showToast({
                  title: `已取消，请手动退出登录并重新登录`,
                  icon: "none",
                });
              });
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
            });
          }
        } catch (error) {
          console.log(error);
        }
      },
    },
  };
</script>

<style>
  /* 打卡日历 */
  .all {
    margin-top: 20rpx;
  }

  .all .bar {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin: 30rpx 20rpx;
    padding: 10rpx;
  }

  .all .bar image {
    width: 50rpx;
    height: 50rpx;
  }

  .all .week {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin: 20rpx;
    border-radius: 10px;
    background-color: #fff;
  }

  .all .days {
    margin: 20rpx;
    padding: 10rpx;
    border-radius: 10px;
    background-color: #fff;
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
  }

  .all .columns {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .all .columns .rows {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }

  .all .columns .rows .active {
    background: #3b87f7;
    width: 80rpx;
    height: 80rpx;
    margin: 3rpx;
    color: #fff;
    text-align: center;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .all .columns .rows .select {
    background: #3b87f7;
    width: 80rpx;
    height: 80rpx;
    margin: 3rpx;
    color: #fff;
    text-align: center;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .all .columns .rows .noSelect {
    background: #83c75d;
  }

  .all .columns .rows .active2 {
    background: #fff;
  }

  .all .columns .rows .cell {
    width: 80rpx;
    height: 80rpx;
    margin: 3rpx;
    text-align: center;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .all .columns .rows .test {
    width: 7rpx;
    height: 7rpx;
    border-radius: 50%;
    margin-left: 39rpx;
    margin-top: 5rpx;
  }

  .all .explain {
    height: 95rpx;
    margin: 10rpx;
    background: #f8f8f8;
  }

  .all .explain .normal {
    width: 15rpx;
    height: 15rpx;
    margin-left: 10rpx;
    border-radius: 50%;
    background: #83c75d;
    display: inline-block;
  }

  .all .explain .abnormal {
    width: 15rpx;
    height: 15rpx;
    margin-left: 10rpx;
    border-radius: 50%;
    background: #fabc05;
    display: inline-block;
  }

  .all .explain .info {
    display: inline-block;
    margin-left: 10rpx;
    font-size: 25rpx;
    color: #8a8f94;
  }

  .count .daynumber {
    display: flex;
    flex-direction: row;
    justify-content: center;
  }

  .count .daynumber .day {
    margin-top: 50rpx;
  }

  .count {
    margin: 20rpx;
    padding: 30rpx;
    display: flex;
    text-align: center;
    border-radius: 10px;
    flex-direction: column;
    justify-content: center;
    background-color: #fff;
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
    align-items: center;
  }

  .count .number {
    color: red;
    font-size: 60rpx;
    background-color: #fff;
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin: 20rpx;
  }

  .count text {
    margin: 10rpx;
  }

  .van-step--vertical:after {
    border-bottom-width: 0px !important;
  }

  .van-step__circle-container {
    height: 0;
  }
</style>